module.exports = (app) => {
  const express = require("express");
  const router = express.Router();
  const resource = require("../../middlewares/resource");
  const auth = require("../../middlewares/auth");
  const bcrypt = require("bcrypt");
  const jwt = require("jsonwebtoken");
  const assert = require("http-assert");

  // 获取资源
  router.get("/", async (req, res) => {
    const { Model } = req
    let { pageSize = 0, pageNumber = 1 } = req.query
    pageSize = parseInt(pageSize)
    pageNumber = parseInt(pageNumber)
    const queryOptions = {
      limit: pageSize,
      skip: ((pageNumber - 1) * pageSize) > 0 ? (pageNumber - 1) * pageSize : 0
    }
    // 按需添加关联查询参数
    if (Model.modelName === "Category") {
      queryOptions.populate = "parent"
    }
    const result = await Model.find(null, null, queryOptions)
    const response = {
      code: 1,
      data: result,
    }
    if ("pageNumber" in req.query && "pageSize" in req.query) {
      const total = await Model.countDocuments()
      response.total = total
      response.page = pageNumber
    }
    // 返回json数据
    res.json(response)
  });

  // 根据id获取资源
  router.get("/:id", async (req, res) => {
    const result = await req.Model.findById(req.params.id)
    res.json({
      code: 1,
      data: result
    })
  });

  // 创建资源
  router.post("/", async (req, res) => {
    const result = await req.Model.create(req.body)
    // 返回json数据
    res.json({
      code: 1,
      data: result
    })
  });

  // 根据id更新资源
  router.put("/:id", async (req, res) => {
    const result = await req.Model.findByIdAndUpdate(req.params.id, req.body)
    res.json({
      code: 1,
      data: result
    })
  });

  // 根据id删除资源
  router.delete("/:id", async (req, res) => {
    await req.Model.findByIdAndDelete(req.params.id)
    res.json({
      code: 1,
      message: "删除成功"
    })
  });

  // 登录接口
  app.post("/admin/api/login", async (req, res) => {
    const { username, password } = req.body;
    const model = require("../../models/AdminUser");
    const user = await model.findOne({ username }).select("+password");

    assert(user, 422, "用户不存在");

    const hasTruePsw = bcrypt.compareSync(password, user.password);

    assert(hasTruePsw, 422, "密码不正确");

    // jwt签名,返回token
    res.json({
      message: "登录成功",
      token: jwt.sign(
        {
          id: user._id
        },
        require("../../config/jwt").secret,
        { expiresIn: "7d" }
      )
    });
  });

  // 注册接口
  app.post("/admin/api/register", async (req, res) => {
    const { username } = req.body;
    const model = require("../../models/AdminUser");
    const user = await model.findOne({ username });

    assert(!user, 422, "用户已存在")

    await model.create(req.body)

    res.json({
      code: 1,
      message: "注册成功"
    })
  })

  // 获取个人信息
  app.get("/admin/api/userinfo", auth(app), async (req, res) => {
    const model = require("../../models/AdminUser");
    const user = await model.findById(req.id).lean()
    delete user.password
    res.json({
      code: 1,
      data: user
    })
  })

  // 上传图片接口
  const multer = require("multer");
  const path = require("path");
  const storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, path.resolve(__dirname, "../../uploads"))
    },
    filename: function (req, file, cb) {
      const filename = file.originalname;
      const mime = filename.split(".").pop();
      cb(null, +Date.now() + '.' + mime)
    }
  })
  const upload = multer({ storage });
  app.post(
    "/admin/api/upload",
    auth(app),
    upload.single("file"),
    (req, res) => {
      // 上传成功
      res.json({
        message: "上传成功",
        file: {
          ...req.file,
          url: "http://localhost:5000/uploads/" + req.file.filename
        }
      });
    }
  );

  // 获取所有的资源
  app.use(
    "/admin/api/rest/:resource",
    auth(app),
    resource(app),
    router
  );
};
